package com.thinkfit.jy.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.common.lib.bean.VideoBean;
import com.common.lib.constant.Constants;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.manager.DataManager;
import com.thinkfit.jy.R;
import com.thinkfit.jy.adapter.LiveVideoAdapter;
import com.thinkfit.jy.contract.LiveVideoContract;
import com.thinkfit.jy.presenter.LiveVideoPresenter;
import com.thinkfit.jy.serialport.SerialPortManager;
import com.thinkfit.jy.serialport.SportType;
import com.thinkfit.jy.utils.BluetoothOrder;
import com.thinkfit.jy.utils.DeviceTypeUtils;
import com.thinkfit.jy.utils.EquipmentInfoUtils;
import com.thinkfit.jy.utils.FastBlurUtility;
import com.thinkfit.jy.utils.MotionDataUtils;
import com.thinkfit.jy.utils.ShowSpeedViewUtils;
import com.thinkfit.jy.utils.SportsDataUtils;
import com.thinkfit.jy.utils.SportsStatusBarViewUtils;
import com.xiao.nicevideoplayer.NiceVideoPlayer;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;

import java.math.BigDecimal;
import java.util.HashMap;

import xyz.doikki.videocontroller.StandardVideoController;
import xyz.doikki.videocontroller.component.GestureView;
import xyz.doikki.videocontroller.component.VodControlView;
import xyz.doikki.videoplayer.player.VideoView;


/**
 * 实景课程运动界面
 */
public class LiveVideoActivity extends MainActivity implements LiveVideoContract.View {

    private LiveVideoAdapter mAdapter;
    private VideoBean mVideo;
    private StandardVideoController mController;
    private NiceVideoPlayer mNiceVideoPlayer;
    private VideoView videoView;
    private boolean mIsInit;
    private int mMainStyle,vtype;

    @Override
    protected int getLayoutId() {
//        mMainStyle = DataManager.Companion.getInstance().getMainStyle();
//        return mMainStyle == 3 ? R.layout.activity_live_video_xm :
        return R.layout.activity_live_video;
    }

    public void init() {
        mIsInit = true;
        mVideo = (VideoBean) getIntent().getSerializableExtra(Constants.BUNDLE_EXTRA);
        vtype = getIntent().getIntExtra(Constants.BUNDLE_EXTRA_2,4);
        if(DeviceTypeUtils.connectDeviceType() == 0){
            BluetoothOrder.getInstance().setSportType(SportType.LIVE);
        }else {
            SerialPortManager.getInstance().setSportType(SportType.LIVE, mVideo.getVideoId());
        }
//        RecyclerView recyclerView = findViewById(R.id.recyclerView);
//        LinearLayoutManager gridLayoutManager = new LinearLayoutManager(this);
//        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//        recyclerView.setLayoutManager(gridLayoutManager);
//        getAdapter().onAttachedToRecyclerView(recyclerView);
//        recyclerView.setAdapter(getAdapter());

//        setViewsOnClickListener(R.id.iv, R.id.ivBack, R.id.ivHome, R.id.ivSound, R.id.ivMore, R.id.emptyView, R.id.ivSlopMinus,
//                R.id.ivSlopAdd, R.id.ivSpeedMinus, R.id.ivSpeedAdd, R.id.llStart,R.id.ivBluetooth);
//        resetInfo(SerialPortManager.getInstance().getCurrentInfo());
//        setTextTypeFace(R.id.tvSlope, R.id.tvSpeed, R.id.tvDistance, R.id.tvTime);
//        if(DeviceTypeUtils.connectDeviceType() == 0){
//            showStartBtn(BluetoothOrder.getInstance().isRun());
//        }else {
//            showStartBtn(SerialPortManager.getInstance().isRun());
//        }

//        if(DeviceTypeUtils.connectDeviceType() == 0){
//            if(BluetoothOrder.getInstance().mCurrentDeviceType.equals(DeviceTypeUtils.SPINNING)
//                    ||BluetoothOrder.getInstance().mCurrentDeviceType.equals(DeviceTypeUtils.ELLIPTICAL_MACHINE)){
//                //动感单车或椭圆机
//                setViewInvisible(R.id.ivSpeedAdd, R.id.ivSpeedMinus);
//            } else if (BluetoothOrder.getInstance().mCurrentDeviceType.equals(DeviceTypeUtils.ROWING_MACHINE)){
//                //划船机
//                setViewInvisible(R.id.ivSpeedAdd, R.id.ivSpeedMinus);
//            }
//        }else {
//            if (SerialPortManager.mCurrentDeviceType == DeviceType.CAR_WATCH) {
//                setViewInvisible(R.id.ivSpeedAdd, R.id.ivSpeedMinus);
//                setText(R.id.tvSlopTitle, R.string.app_resistance);
//                setText(R.id.tvSpeedTitle, R.string.app_pace_500m);
//                setViewGone(R.id.ivSpeedAdd, R.id.ivSpeedMinus);
//            }
//        }
//        getNiceVideoPlayer().continueFromLastPosition(false);
        SportsDataUtils.getInstance().setSportType(SportType.LIVE);
        ((LiveVideoContract.Presenter) getPresenter()).getLiveVideoDetail(mVideo.getVideoId(),vtype);
        showVideo();

    }

    public void showUserInfo() {

    }
    MediaPlayer mediaPlayer;
    private void showVideo() {
//        getNiceVideoPlayer().setPlayerType(NiceVideoPlayer.TYPE_NATIVE);//这个没办法设置播放速度
//        getNiceVideoPlayer().setPlayerType(NiceVideoPlayer.TYPE_IJK);//变更播放速度会变卡
        mController = new StandardVideoController(this);
//        mController.setTitle("");
//        getNiceVideoPlayer().setController(mController);
        getVideoPlayer().setVideoController(mController);
        VodControlView vodControlView = new VodControlView(this);//点播控制条
        GestureView gestureView = new GestureView(this);
        vodControlView.showBottomProgress(false);

        mController.addControlComponent(vodControlView);
        mController.addControlComponent(gestureView);
        //竖屏也开启手势操作，默认关闭
        mController.setEnableInNormal(true);
        //滑动调节亮度，音量，进度，默认开启
        mController.setGestureEnabled(true);
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   Video.Url =  "+ mVideo.getUrl());
        if (!TextUtils.isEmpty(mVideo.getUrl())) {
//            String path = mVideo.getUrl().replace(" ","%20");
//            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   Video.Url =  "+ path);
            getVideoPlayer().setUrl(mVideo.getUrl(), null);
//            getNiceVideoPlayer().setUp("http" + Objects.requireNonNull(mVideo.getUrl()).substring(5), null);//"http" + Objects.requireNonNull(mVideo.getUrl()).substring(5), null);
        }

//        getVideoPlayer().getTitleTextView().setVisibility(View.GONE);
//        getVideoPlayer().getBackButton().setVisibility(View.GONE);
//        getVideoPlayer().enterWindowFullscreen();//全屏
//        getNiceVideoPlayer().continueFromLastPosition(false);
//        BaseUtils.StaticParams.loadImage(this, 0, mVideo.getCover(), findViewById(R.id.iv));
        findViewById(R.id.iv).setVisibility(View.GONE);
    }


    /**
     * 获取播放器
     * @return
     */
//    private NiceVideoPlayer getNiceVideoPlayer() {
//        if (mNiceVideoPlayer == null) {
//            mNiceVideoPlayer = findViewById(R.id.videoView);
//        }
//        return mNiceVideoPlayer;
//    }

    private VideoView getVideoPlayer() {
        if (videoView == null) {
            videoView = findViewById(R.id.videoView);
        }
        return videoView;
    }



    /**
     * 停止初始化控件
     */
    public void initWidget(){
//        getVideoPlayer().pause();
        getVideoPlayer().pause();
        setText(R.id.tvSlope, "0");
        setText(R.id.tvSpeed, "0.0");
        setText(R.id.tvDistance, "0.0");
        setText(R.id.tvTime, "00:00");
    }


    @NonNull
    @Override
    protected LiveVideoContract.Presenter onCreatePresenter() {
        return new LiveVideoPresenter(this);
    }

    boolean mIsStart = false;

    @Override
    public void onReceive(HashMap<String, Object> map) {
        if (map == null) {
            return;
        }
        super.onReceive(map);
        if(map.containsKey(EventBusEvent.KILL_ACTIVITY)){
//            HashMap<String, Object> map1 = new HashMap<>();
//            map1.put(EventBusEvent.STOP_RUN,"");
//            EventBus.getDefault().post(map1);
            finish();
        }else if (map.containsKey(EventBusEvent.PAUSE_RUN)) {
            System.out.println("BluetoothOrder ------------->  STOP_RUN : 1");
            NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
            getVideoPlayer().pause();
//                getNiceVideoPlayer().pause();
//            showStartBtn(false);
            mIsStart = false;
//            initWidget();
//            ShowSpeedViewUtils.getInstance().goneLayout();
        }else if(map.containsKey(EventBusEvent.START_RUN)){
            getVideoPlayer().start();
            mIsStart = true;
        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llStart:
                if (SerialPortManager.getInstance().isConnected()||BluetoothOrder.getInstance().isConnect()) {
                    super.onClick(v);
                } else {
                    if (!mIsStart) {
//                        getNiceVideoPlayer().start(1);
                        getVideoPlayer().start();
                        showStartBtn(true);
                        mIsStart = true;

                    } else {
                        getVideoPlayer().pause();
//                        getNiceVideoPlayer().pause();
//                        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
                        showStartBtn(false);
                        mIsStart = false;
                    }
                }
                break;
            case R.id.ivBack:
//                if (!SerialPortManager.getInstance().isRun()) {
//                    finish();
//                    return;
//                }
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                Intent intent = new Intent(this, DialogActivity.class);
                intent.putExtra(Constants.BUNDLE_EXTRA, DialogActivity.END_SPORT_BACK);
                startActivity(intent);
                break;
            case R.id.ivHome:
//                if (!SerialPortManager.getInstance().isRun()) {
//                    toHomeActivity();
//                    return;
//                }
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                intent = new Intent(this, DialogActivity.class);
                intent.putExtra(Constants.BUNDLE_EXTRA, DialogActivity.END_SPORT_TO_HOME);
                startActivity(intent);
                break;
            case R.id.ivMore:
                setViewVisible(R.id.ll);
                setViewGone(R.id.ivMore);
                break;
            case R.id.emptyView:
                setViewGone(R.id.ll);
                setViewVisible(R.id.ivMore);
                break;
            case R.id.ivSpeedAdd:
                resetSpeed(true);
                break;
            case R.id.ivSpeedMinus:
                resetSpeed(false);
                break;
            case R.id.ivSlopAdd:
                resetSlop(true);
                break;
            case R.id.ivSlopMinus:
                resetSlop(false);
                break;
            default:
                super.onClick(v);
                break;
        }
    }

    private void resetSpeed(boolean isAdd) {
        BigDecimal speed = new BigDecimal(getTextById(R.id.tvSpeed));
        if (isAdd) {
            speed = speed.add(new BigDecimal("0.1"));//加速
        } else {
            speed = speed.subtract(new BigDecimal("0.1"));//减速
        }
        if (speed.compareTo(BigDecimal.ZERO) < 0) {
            return;
        }
        int slop;
        int speedNum = speed.multiply(BigDecimal.TEN).intValue();
        if(DeviceTypeUtils.connectDeviceType() == 0){
            slop = MotionDataUtils.getInstance().getCurrentInfo().slop;
            BluetoothOrder.getInstance().setNowelAndSlope(speedNum,slop);
        }else {
            slop = MotionDataUtils.getInstance().getCurrentInfo().slop;
            SerialPortManager.getInstance().setSpeedSlop(speedNum, slop);
        }
        float videoSpeed = speedNum/ EquipmentInfoUtils.getInstance().getEquipmentInfoBean().getResistance();
//        getNiceVideoPlayer().setSpeed(2.0f);//视频播放速度设置
        System.out.println("ddddddddddddddddddddddd  videoSpeed 222 : "+videoSpeed);
//        getNiceVideoPlayer().setSpeed(videoSpeed+1);//视频播放速度设置

        setPlaySpeed(videoSpeed);

    }

    private void resetSlop(boolean isAdd) {
        BigDecimal value = new BigDecimal(getTextById(R.id.tvSlope));
        if (isAdd) {
            value = value.add(new BigDecimal("1"));
        } else {
            value = value.subtract(new BigDecimal("1"));
        }
        if (value.compareTo(BigDecimal.ZERO) < 0) {
            return;
        }
        if(DeviceTypeUtils.connectDeviceType() == 0){
            if (MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)){
                if (value.intValue() < 0) {
                    return;
                }
                int speed = MotionDataUtils.getInstance().getCurrentInfo().speed;
                BluetoothOrder.getInstance().setNowelAndSlope(speed,value.intValue());

            }else {

                if (value.intValue() < 0 || value.intValue() > 32) {
                    return;
                }
                int slop = MotionDataUtils.getInstance().getCurrentInfo().slop;
                BluetoothOrder.getInstance().setNowelAndSlope(value.intValue(), slop);
            }
        }else {
            if (MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)) {
                if (value.intValue() < 0) {
                    return;
                }
                int speed = MotionDataUtils.getInstance().getCurrentInfo().speed;
                SerialPortManager.getInstance().setSpeedSlop(speed, value.intValue());
            } else {
                if (value.intValue() < 0 || value.intValue() > 32) {
                    return;
                }
                int slop = MotionDataUtils.getInstance().getCurrentInfo().slop;
                SerialPortManager.getInstance().setSpeedSlop(value.intValue(), slop);
//                SerialPortManager.getInstance().setResistanceSlop(value.intValue(), slop);
            }
        }

        float videoSpeed = (float) value.intValue()/ EquipmentInfoUtils.getInstance().getEquipmentInfoBean().getResistance();
        System.out.println("ddddddddddddddddddddddd  videoSpeed 111 : "+videoSpeed);
//        getNiceVideoPlayer().setSpeed(videoSpeed+1);//视频播放速度设置
        setPlaySpeed(videoSpeed);
//        System.out.println("ddddddddddddddddddddddd  videoSpeed 111 : "+getVideoPlayer().getSpeed());
    }

    private void setPlaySpeed(float speed) {
//        getVideoPlayer().setSpeed(speed);
    }

    private LiveVideoAdapter getAdapter() {
        if (mAdapter == null) {
            mAdapter = new LiveVideoAdapter(this);
            mAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    setViewGone(R.id.ll);
                    setViewVisible(R.id.ivMore);
//                    getNiceVideoPlayer().seekTo(mAdapter.getItem(position).getStartime() * 1000L);
                }
            });
        }
        return mAdapter;
    }

    @Override
    public void getLiveVideoDetailSuccess(VideoBean detail) {
        if (isFinish() || detail == null) {
            return;
        }
        if (DataManager.Companion.getInstance().isLogin()) {
            ((LiveVideoContract.Presenter) getPresenter()).addVideoRecord(mVideo.getVideoId());
        }
//        mDuration = detail.getAlltime();
//        vburst = detail.getVburst();
//        getMultiProgressView().initData(mDuration, vburst);
        getAdapter().setNewInstance(detail.getVburst());
        if(!mIsStart){
            getVideoPlayer().start();
//            getNiceVideoPlayer().start(1);
            mIsStart = true;
            ShowSpeedViewUtils.getInstance().initView(getApplicationContext());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        ShowSpeedViewUtils.getInstance().initView(getApplicationContext());
        SportsStatusBarViewUtils.getInstance().initView(getApplicationContext());
        SportsStatusBarViewUtils.getInstance().isPlayVideo(true);
        if(mIsStart){
            getVideoPlayer().start();
//            getNiceVideoPlayer().start(1);
        }
        SportsStatusBarViewUtils.getInstance().setHomeView(false);

    }

    @Override
    protected void onStop() {
        super.onStop();
        if(mIsStart){
//            getVideoPlayer().pause();
            getVideoPlayer().pause();
        }

    }

    public void onDestroy() {
        super.onDestroy();

//        getVideoPlayer().stopPlayback();
        SportsStatusBarViewUtils.getInstance().isPlayVideo(false);
        getVideoPlayer().pause();
        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
        ShowSpeedViewUtils.getInstance().goneLayout();
    }

    public void showStartBtn(boolean isRun) {
        super.showStartBtn(isRun);
        if (isRun) {
            setViewGone(R.id.iv);
            if (mIsInit) {
                getVideoPlayer().start();
                mIsInit = false;
            } else {
                getVideoPlayer().start();
            }
//            if (SerialPortManager.getInstance().isPause()) {
//                getVideoPlayer().pause();
////                getVideoPlayer().pause();
//            } else {
//                if (mIsInit) {
//                    getVideoPlayer().start();//第一次播放用start
////                    getVideoPlayer().start();
//                    mIsInit = false;
//                } else {
//                    getVideoPlayer().start();//继续播放使用reStart
////                    getVideoPlayer().start();
//                }
//            }
        } else {
            NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();//回收播放器资源
            mIsInit = true;
        }
    }

    public void setViewsAlpha(float alpha, int... viewIds) {

    }

    public void resetInfo(SerialPortManager.CurrentInfo info) {
//        super.resetInfo(info);
//        int speed = info.speed;
//        if (SerialPortManager.mCurrentDeviceType == DeviceType.RUNNING_MACHINE) {
//            if (speed < 50) {   //2km/h
//                getNiceVideoPlayer().setSpeed(0.5f);
//            } else if (speed < 80) {
//                getNiceVideoPlayer().setSpeed(0.8f);
//            } else if (speed < 150) {
//                getNiceVideoPlayer().setSpeed(1f);
//            } else if (speed < 220) {
//                getNiceVideoPlayer().setSpeed(1.25f);
//            } else {
//                getNiceVideoPlayer().setSpeed(1.5f);
//            }
//        } else if (SerialPortManager.mCurrentDeviceType == DeviceType.CAR_WATCH) {
//            if (speed < 20) {   //2km/h
//                getNiceVideoPlayer().setSpeed(0.5f);
//            } else if (speed < 40) {
//                getNiceVideoPlayer().setSpeed(0.8f);
//            } else if (speed < 60) {
//                getNiceVideoPlayer().setSpeed(1f);
//            } else if (speed < 80) {
//                getNiceVideoPlayer().setSpeed(1.25f);
//            } else {
//                getNiceVideoPlayer().setSpeed(1.5f);
//            }
//        }
//        getMultiProgressView().setProgress(current);
    }

    @Override
    public boolean isMainActivity() {
        return false;
    }

}